import React, { Component, createRef } from 'react'

import echarts from 'echarts'
import { Card, Row, Col, Button, Spin } from 'antd'

import { getReadingQuantityByMonths } from '../../requests'

export default class Dashboard extends Component {
  constructor() {
    super()
    this.readingQuantity = createRef()
    this.state = {
      readingQuantityMonths: 6,
      spinning: true
    }
  }

  setReadingQuantityChartOptions = data => {
    const xAxisData = data.map(item => item.month)
    const seriesData = data.map(item => item.quantity)
    this.readingQuantityChart.setOption({
      tooltip: {},
      xAxis: {
        data: xAxisData
      },
      yAxis: {},
      series: [
        {
          name: '阅读量',
          type: 'line',
          smooth: true,
          data: seriesData
        }
      ]
    })
  }

  getReadingQuantity = () => {
    getReadingQuantityByMonths(this.state.readingQuantityMonths).then(resp => {
      if (resp.data.code === 200) {
        this.setReadingQuantityChartOptions(resp.data.data)
        this.setState({
          spinning: false
        })
      }
    })
  }

  handleReadingQuantityMontesChange(month) {
    this.setState(
      {
        readingQuantityMonths: month
      },
      () => {
        this.getReadingQuantity()
      }
    )
  }

  componentDidMount() {
    this.readingQuantityChart = echarts.init(this.readingQuantity.current)
    this.getReadingQuantity()
  }

  render() {
    return (
      <Spin spinning={this.state.spinning}>
        <Row>
          <Col span={12}>
            <Button.Group>
              <Button
                type={
                  this.state.readingQuantityMonths === 3 ? 'primary' : 'default'
                }
                onClick={this.handleReadingQuantityMontesChange.bind(this, 3)}
              >
                近三月
              </Button>
              <Button
                type={
                  this.state.readingQuantityMonths === 6 ? 'primary' : 'default'
                }
                onClick={this.handleReadingQuantityMontesChange.bind(this, 6)}
              >
                近六月
              </Button>
              <Button
                type={
                  this.state.readingQuantityMonths === 12
                    ? 'primary'
                    : 'default'
                }
                onClick={this.handleReadingQuantityMontesChange.bind(this, 12)}
              >
                近一年
              </Button>
            </Button.Group>
            <Card style={{ border: 'none' }}>
              <div
                ref={this.readingQuantity}
                style={{ height: 300 }}
                //   loading={this.state.isLoading}
              />
            </Card>
          </Col>
        </Row>
      </Spin>
    )
  }
}
